package com.hubeiweb.controller;

import com.hubeiweb.exception.CustomException;
import com.hubeiweb.service.FileUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class FileController {

    @Autowired
    private FileUploadService uploadService;

    @RequestMapping("/file_upload.action")
    public String visitFile(){

        return "upload_file";
    }
    @RequestMapping("/save_upload.action")
        public String saveFile(HttpServletRequest request, MultipartFile file){
        //通过请求对象获得application全局内置对象,通过application全局对象,获取应用在服务器部署的物理路径
        HttpSession session = request.getSession();
        ServletContext application = session.getServletContext();

        String realpath = application.getRealPath("/");
        realpath=realpath.replace("\\", "/")+"files";
        if(file!=null){
            String filename = file.getOriginalFilename();
            //获得文件类型
            int index = filename.lastIndexOf(".");
            String type = filename.substring(index);
            String newName=dealTime() + UUID.randomUUID()+type;
            //创建一个新的文件对象
            File saveFile = new File(realpath, newName);
            try {
                file.transferTo(saveFile);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //存储数据
            Map<String,String> map = new HashMap<>();
            map.put("name",filename);
            map.put("path","/files/"+newName);
            uploadService.saveFile(map);
        }else {
            throw new CustomException("没有文件上传");
        }
            return "redirect:upload_list.action";
        }
        @RequestMapping("upload_list.action")
        public String queryList(Model  model){
            List<Map<String, String>> list = uploadService.queryList();
            model.addAttribute("fileList",list);
            return "upload_file";
        }


        private  String dealTime(){
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
        }

    }

